#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>

int client_fd;
void fun_send(int num)
{
	char buf[64] = "";
	scanf("%s",buf);
	getchar();
	send(client_fd, buf, strlen(buf),0);
	memset(buf,0,64);
}
int main(int argc,const char *argv[])
{
	int server_fd;
	int ret;
	char buf[64] = "";
	struct sockaddr_in server_addr,client_addr;
	socklen_t addrlen = sizeof(struct sockaddr_in);

	server_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(server_fd == -1)
	{
		perror("fail to socket");
		return -1;
	}
	memset(&server_addr,0,sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(argv[2]));
	server_addr.sin_addr.s_addr = inet_addr(argv[1]);

	ret = bind(server_fd, (struct sockaddr *)&server_addr,sizeof(server_addr));
	if(ret == -1)
	{
		perror("fail to bind");
		return -1;
	}
	ret = listen(server_fd, 5);
	if(ret == -1)
	{
		perror("fail to listen");
		return -1;
	}
	client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addrlen);
	if(client_fd == -1)
	{
		perror("fail to accept");
		return -1;
	}
//	signal(SIGINT,fun_send);
	printf("client addr:%s\n",inet_ntoa(client_addr.sin_addr));
	while(1)
	{
		ret = recv(client_fd, buf, 64, 0);
		if(ret > 0)
		{
			printf("%s\n",buf);
			memset(buf,0,64);
		}
		else if(ret < 0)
		{
			perror("fail to recv\n");
			close(client_fd);
			close(server_fd);
			return -1;
		}
		else
		{
			printf("peer exit\n");
			close(client_fd);
			close(server_fd);
			return 0;
		}
	}
	return 0;
}
